#include <sys/unistd.h>
#include <sys/stat.h>
#include "esp_vfs_fat.h"
#include "sdmmc_cmd.h"
#include "driver/sdmmc_host.h"
#include "sd.h"
static const char *TAG = "example";
#define MOUNT_POINT "/sdcard"
sdmmc_card_t *card;
const char mount_point[] = MOUNT_POINT;
void sdmmc_init()
{  
    ESP_LOGI(TAG, "Initializing SD card");
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {
#ifdef CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED
    .format_if_mount_failed = true,
#else
    .format_if_mount_failed = false,
#endif // EXAMPLE_FORMAT_IF_MOUNT_FAILED
    .max_files = 5,
    .allocation_unit_size = 16 * 1024
    };
    //使用上面定义的设置初始化SD卡并挂载FAT文件系统。
    //备注:esp_vfs_fat_sdmmc/sdspi_mount是一体化的方便函数。
    //请查看源代码，并在开发时实现错误恢复
    sdmmc_host_t host = SDMMC_HOST_DEFAULT();
    ESP_LOGI(TAG, "Using SDMMC peripheral");

    sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
    slot_config.width = 1;    // Set bus width to use:
    slot_config.clk = GPIO_NUM_3;
    slot_config.cmd = GPIO_NUM_4;
    slot_config.d0 = GPIO_NUM_0;
    slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP;//需要外部给上拉电阻10k

    esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
    //mountpoint：指定要挂载到的目录路径，例如 "/sdcard"；
    //host_config：SD/MMC 主机配置，可以为空指针；
    //slot_config：SD/MMC 卡槽配置，可以为空指针；
    //mount_config：FAT 文件系统挂载配置结构体，用于配置文件系统的相关参数；
    //out_card：初始化后的 SD/MMC 卡片句柄，输出参数。
    sdmmc_card_print_info(stdout, card);
    sdmmc_handler();

}

void sdmmc_handler()
{
    const char *file_hello = MOUNT_POINT"/hello.txt";
    const char *chen_hello = MOUNT_POINT"/chen.txt";
    FILE *f1 = fopen(file_hello, "r");
    char buff[64];
    fats_read_text_all(chen_hello,buff);

    FILE *f = fopen(file_hello, "w");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for writing");
        return;
    }
    fprintf(f, "Hello %s!\n", card->cid.name);
    fprintf(f,buff);
    fclose(f);
    ESP_LOGI(TAG, "File written");
    esp_vfs_fat_sdcard_unmount(mount_point, card);
}
/*
*将文件file里的所有数据读取到buff里（文本文件用）
*返回值：整个文件的字节数
*/
long fats_read_text_all(const char* file,char* buff)
{
FILE* fp = fopen(file, "r");
if (fp == NULL) {
    printf("Failed to open file.\n");
    return;
}
fseek(fp, 0, SEEK_END);
long fileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
fgets(buff,fileSize,fp);
return fileSize;
}
/*
*将文件file里的所有数据读取到buff里（二进制文件件用）
*返回值：整个文件的字节数
*/
long fats_read_bin_all(const char* file,char* buff)
{
FILE* fp = fopen(file, "r");
if (fp == NULL) {
    printf("Failed to open file.\n");
    return;
}
fseek(fp, 0, SEEK_END);
long fileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
fread(buff,sizeof(char),sizeof(buff),fp);
return fileSize;
}

    
